<?php

#=============================
# Define cache directory
#=============================
define('CACHE_DIR', constant('SITE_PATH') . 'cache/');

class cache {

	var $zam;
	var $data = array();
	
	function cache()
	{
		$this->load_cache();
	}
	
	#=============================
	# Build cache or add cache
	#=============================
	function build_cache($key, $values)
	{
		$key = constant('CACHE_DIR') . base64_encode( substr($key, 0, 50) ) . '.ZAM';
		
		if ( !is_array($values) )
		{
			$values = array($values);
		}
		
		if ( file_exists($key) )
		{
			$cache = file_get_contents( $key );
			$cache = unserialize( base64_decode( $cache ) );
			$cache = @array_merge($cache, $values);
		}
		else
		{
			$cache = $values;
		}
		
		$cache = base64_encode( serialize( $cache ) );
		
		$fp = file_put_contents( $key, $cache );
		@chmod($key, 0777);
	}
	
	#==============================
	# Load cache from file
	#==============================
	function load_cache()
	{
		if ( $dh = @opendir( constant('CACHE_DIR') ) )
		{
			while ( $cache = readdir($dh) )
			{
				if ( !preg_match('/^(.+?)\.ZAM$/', $cache) )
				{
					continue;
				}
				
				$ckey = base64_decode( str_replace( '.ZAM', '', $cache ) );
				$cvalue = unserialize( base64_decode( file_get_contents( constant('CACHE_DIR') . $cache ) ) );
				$this->data[ $ckey ] = $cvalue;
			}
		}
	}
	
	#==============================
	# Clear cache file
	#==============================
	function clear_cache($key='')
	{
		if ( !empty($key) )
		{
			$key = constant('CACHE_DIR') . base64_encode( $key ) . '.ZAM';
			if ( file_exists($key) )
			{
				@unlink($key);
			}
		
			$this->data[$key] = array();
		}
		else
		{
			if ( $dh = @opendir( constant('CACHE_DIR') ) )
			{
				while ( $cache = readdir($dh) )
				{
					if ( !preg_match('/^(.+?)\.ZAM$/', $cache) )
					{
						continue;
					}
					
					@unlink( constant('CACHE_DIR') . $cache );
				}
			}
			
			$this->data = array();
		}
	}
}

?>